package com.achobeta.recruitment.component;

import com.achobeta.recruitment.model.Message;
import com.achobeta.recruitment.utils.TokenUtils;
import com.achobeta.recruitment.utils.HttpUtils;
import com.achobeta.recruitment.utils.JsonUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.util.HashMap;
import java.util.Map;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: 马拉圈
 * Date: 2023-10-27
 * Time: 0:28
 */
@Component
public class ModelMessageSender {

    @Value("${wx.appid}")
    private String appId;

    @Value("${wx.secret}")
    private String secret;

    @Value("${recruit.template_id}")
    private String templateId;

    private Map<String, Object> getKeyword(int index, String value) {
        return new HashMap<String, Object>(){{
            this.put("keyword" + index, new HashMap<String, Object>(){{
                this.put("value", value);
            }});
        }};
    }
    public String sendModelMessage(Message message) {
        String url = "https://api.weixin.qq.com/cgi-bin/message/template/send" + HttpUtils.getQueryString(new HashMap<String, Object>() {{
            this.put("access_token", TokenUtils.getToken(appId, secret));
        }});
        Map<String, Object> data = new HashMap<String, Object>(){{
            this.putAll(getKeyword(1, message.getTitle()));
            this.putAll(getKeyword(2, message.getContent()));
        }};

        Map<String, Object> param = new HashMap<String, Object>() {{
            this.put("touser", message.getOpenid());
            this.put("template_id", templateId);
            this.put("url", message.getUrl());
            this.put("data", data);
        }};
        // 发送请求
        return HttpUtils.doPost(url, JsonUtils.objectToJson(param));
//        return "";
    }

}
